<template>
  <div class="login-wrap">
    <el-form label-position="left" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="0px" class="demo-ruleForm login-container">
      <h3 class="title">用户登录</h3>
      <!-- 用户信息 -->
      <el-form-item prop="username">
        <el-input type="text" v-model="ruleForm.username" auto-complete="off" placeholder="账号"></el-input>
      </el-form-item>
      <!-- 密码 -->
      <el-form-item prop="password">
        <el-input type="password" v-model="ruleForm.password" auto-complete="off" placeholder="密码"></el-input>
      </el-form-item>
      <!-- 图形验证码生成器 -->
      <el-row>
        <el-col :span="8">
          <el-form-item prop="code">
            <el-input type="text" v-model="ruleForm.code" auto-complete="off" placeholder="图形验证码" @keyup.enter.native="submitForm('ruleForm')"></el-input>
          </el-form-item>
        </el-col>
        <!-- 获取验证码 -->
        <el-col :span="16" class="code-box">
          <!-- <img :src="ruleForm.codeimg" alt="" class="codeimg" @click="getcode()"> -->
          <canvas id="CommonGraphicVerificationCodeGeneratorCanvas"
            class="common-graphic-verification-code-generator"
            :src="ruleForm.codeimg"
            @click="getcode()">
          </canvas>
        </el-col>
      </el-row>
      <el-checkbox class="remember" v-model="rememberpwd">记住密码</el-checkbox>
      <el-form-item style="width:100%;">
        <el-button type="primary" style="width:100%;" @click="submitForm('ruleForm')" :loading="logining">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script type="text/ecmascript-6">
import { login } from '../api/userMG'
import { setCookie, getCookie, delCookie } from '../utils/util'
import md5 from 'js-md5'
export default {
  name: 'login',
  data() {
    return {
      //定义loading默认为false
      logining: false,
      // 记住密码
      rememberpwd: false,
      ruleForm: {
        //username和password默认为空
        username: '',
        password: '',
        code: '',
        randomStr: '',
        codeimg: ''
      },
      //rules前端验证
      rules: {
        username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
      }
    }
  },
  // 创建完毕状态(里面是操作)
  created() {
    this.$message({
      message: '账号密码及验证码不为空即可',
      type: 'success'
    })
    // 获取存在本地的用户名密码
    this.getuserpwd()
  },
  mounted () {
    // 获取图形验证码
    this.getcode()
  },
  // 里面的函数只有调用才会执行
  methods: {
    // 获取用户名密码
    getuserpwd() {
      if (getCookie('user') != '' && getCookie('pwd') != '') {
        this.ruleForm.username = getCookie('user')
        this.ruleForm.password = getCookie('pwd')
        this.rememberpwd = true
      }
    },
    //获取info列表
    submitForm(formName) {
      console.log('登录信息：', this.ruleForm)
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.ruleForm.code === this.ruleForm.codeimg) {
            // 验证码输入相同才能登录
            this.logining = true
            // 测试通道，不为空直接登录
            setTimeout(() => {
              this.logining = false
              this.$store.commit('login', 'true')
              this.$router.push({ path: '/goods/Goods' })
            }, 1000)
          } else {
            this.$message.error('验证码输入错误！')
            this.logining = false
            // 需要重新生成图片验证码
            this.getcode()
          }
          // 注释
          // login(this.ruleForm).then(res => {
          //   if (res.success) {
          //     if (this.rememberpwd) {
          //       //保存帐号到cookie，有效期7天
          //       setCookie('user', this.ruleForm.username, 7)
          //       //保存密码到cookie，有效期7天
          //       setCookie('pwd', this.ruleForm.password, 7)
          //     } else {
          //       delCookie('user')
          //       delCookie('pwd')
          //     }
          //     //如果请求成功就让他2秒跳转路由
          //     setTimeout(() => {
          //       this.logining = false
          //       // 缓存token
          //       localStorage.setItem('logintoken', res.data.token)
          //       // 缓存用户个人信息
          //       localStorage.setItem('userdata', JSON.stringify(res.data))
          //       this.$store.commit('login', 'true')
          //       this.$router.push({ path: '/goods/Goods' })
          //     }, 1000)
          //   } else {
          //     this.$message.error(res.msg)
          //     this.logining = false
          //     return false
          //   }
          // })
        } else {
          // 获取图形验证码
          this.getcode()
          this.$message.error('请输入用户名密码！')
          this.logining = false
          return false
        }
      })
    },
    // getGraphicVerificationCode () {
    getcode () {
      var showNum = []
      // document.getElementById('canvas').style.width;
      var canvasWidth = 200
      // document.getElementById('canvas').style.height;
      // var canvasHeight = 50
      var canvasHeight = 100
      // 获取到canvas的对象，景色
      // var canvas = document.getElementById('canvas')
      var canvas = document.getElementById('CommonGraphicVerificationCodeGeneratorCanvas')
      // 获取到canvas画图的环境，景色呈现的画布
      var context = canvas.getContext('2d')
      canvas.width = canvasWidth
      canvas.height = canvasHeight
      var sCode =
        'A,B,C,E,F,G,H,J,K,M,N,P,Q,R,S,T,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0'
      var aCode = sCode.split(',')
      // 获取到数组的长度
      var aLength = aCode.length
      for (let i = 0; i <= 3; i++) {
        // 获取到随机的索引值
        let j = Math.floor(Math.random() * aLength)
        // 产生0~30之间的随机弧度
        let deg = (Math.random() * 30 * Math.PI) / 180
        // 得到随机的一个内容
        let txt = aCode[j]
        showNum[i] = txt.toLowerCase()
        // 文字在canvas上的x坐标
        let x = 10 + i * 40
        // 文字在canvas上的y坐标
        let y = 40 + Math.random() * 8
        context.font = 'bold 23px 微软雅黑'

        context.translate(x, y)
        context.rotate(deg)

        context.fillStyle = this.randomColor()
        context.fillText(txt, 0, 0)

        context.rotate(-deg)
        context.translate(-x, -y)
      }
      for (let i = 0; i <= 5; i++) {
        // 验证码上显示线条
        context.strokeStyle = this.randomColor()
        context.beginPath()
        context.moveTo(
          Math.random() * canvasWidth,
          Math.random() * canvasHeight
        )
        context.lineTo(
          Math.random() * canvasWidth,
          Math.random() * canvasHeight
        )
        context.stroke()
      }
      for (let i = 0; i <= 30; i++) {
        // 验证码上显示小点
        context.strokeStyle = this.randomColor()
        context.beginPath()
        let x = Math.random() * canvasWidth
        let y = Math.random() * canvasHeight
        context.moveTo(x, y)
        context.lineTo(x + 1, y + 1)
        context.stroke()
      }
      // 将showName的数组拼接成一个字符串
      let verificationCodeValue = ''
      showNum.forEach((item, index) => {
        verificationCodeValue += item
      })
      console.log('图像验证码：', verificationCodeValue)
      this.ruleForm.codeimg = verificationCodeValue
      // this.$emit('getVerificationCodeValue', verificationCodeValue)
    },
    randomColor () {
      // 得到随机的颜色值
      let r = Math.floor(Math.random() * 256)
      let g = Math.floor(Math.random() * 256)
      let b = Math.floor(Math.random() * 256)
      return 'rgb(' + r + ',' + g + ',' + b + ')'
    },
  }
}
</script>

<style scoped>
.login-wrap {
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  padding-top: 10%;
  background-image: url();
  /* background-color: #112346; */
  background-repeat: no-repeat;
  background-position: center right;
  background-size: 100%;
}
.login-container {
  border-radius: 10px;
  margin: 0px auto;
  width: 350px;
  padding: 30px 35px 15px 35px;
  background: #fff;
  border: 1px solid #eaeaea;
  text-align: left;
  box-shadow: 0 0 20px 2px rgba(0, 0, 0, 0.1);
}
.title {
  margin: 0px auto 40px auto;
  text-align: center;
  color: #505458;
}
.remember {
  margin: 0px 0px 35px 0px;
}
.code-box {
  text-align: right;
}
.codeimg {
  height: 40px;
}
.common-graphic-verification-code-generator {
  border-style: solid;
  border-width: 1px;
  border-color: gainsboro;
  width: 200px;
  height: 80px;
  background-color: blanchedalmond;
}

</style>
